package com.flow.framework.core.validation.validator;

import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.core.validation.annotation.SizeCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;

import javax.validation.ConstraintValidatorContext;
import java.util.Collection;
import java.util.Map;

/**
 * Size 校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
public class SizeValidator extends BaseValidator<SizeCustomization, Object> {

    private SizeCustomization sizeCustomization;

    private int minSize;

    private int maxSize;

    private String errorMsg;

    @Override
    public void initialize(SizeCustomization sizeCustomization) {
        this.sizeCustomization = sizeCustomization;
        this.minSize = sizeCustomization.min();
        this.maxSize = sizeCustomization.max();
        this.errorMsg = "size is not between " + minSize + " and " + maxSize;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }
        if (value instanceof Collection) {
            int len = ((Collection) value).size();
            if (len < minSize || len > maxSize) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(sizeCustomization.errorCode());
            }
            return true;
        }

        if (value instanceof Map) {
            int len = ((Map) value).size();
            if (len < minSize || len > maxSize) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(sizeCustomization.errorCode());
            }
            return true;
        }
        return false;
    }
}
